//
//  RSOauthViewController.swift
//  RSWeibo
//
//  Created by Macx on 16/8/9.
//  Copyright © 2016年 Macx. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

// 放在外面, 别的控制器也能访问

// appkey
let appKey: String = "2029664191"
// appSecrect
let appSecrect: String = "8713455cc4a5cb487970f0ca09530527"
// 请求回调的网页
let callBakeUrl: String = "http://www.itcast.cn"



class RSOauthViewController: UIViewController {
    
    //  MARK:   -- 懒加载
    private lazy var webView: UIWebView = UIWebView()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        

        setNavUI()
        
        setWebView()
        
       requestWed(appKey, callBakeUrl: callBakeUrl)
        // 设置代理
      webView.delegate = self

        
    }
    
    
    // MARK: 设置导航栏的两个按钮
    private func setNavUI(){
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "cancelActionClick")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "autoAddActionClick")
        

    }
    // MARK: 两个按钮的点击方法
    @objc private func cancelActionClick(){

        dismissViewControllerAnimated(true, completion: nil)
        
    }
    @objc private func autoAddActionClick(){
        
        /*
         使用 stringByEvaluatingJavaScriptFromString 混编
         */
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'rosan2016bj@sina.com';document.getElementById('passwd').value = 'aa19911109rs'")
      
        
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    // MARK:设置网页显示器
    private func setWebView(){
      
        webView = UIWebView(frame: UIScreen.mainScreen().bounds)
        // 把网页设成透明的
        webView.opaque = false
        
        view = webView
 
        
    }
    
    // MARK: 请求第三方登录界面
    private func requestWed(appKey: String, callBakeUrl: String){
    
        // 字符串
        var urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(callBakeUrl)"

        // 转路径
        var url = NSURL(string: urlStr)
        
        // 请求
        var request = NSURLRequest(URL: url!)
        
        
        // 请求页面
        webView.loadRequest(request)
        
    }

}

// 获取 code
extension RSOauthViewController{
    
    /*
     这个方法在实际开发中经常会用到
     */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        guard let url = request.URL else{
            
            return false
        }
        
        // 执行到此, url肯定有值
        
        // 如果返回的url中没有这个前缀, 就继续加载
        if !url.absoluteString.hasPrefix(callBakeUrl) {
            return true
        }
        
        // 代码走到这里, 说明在回调的页面代码里面已经有了刚刚那个字符串
        if let query = url.query where query.hasPrefix("code=") {
            //  获取code
            
            let code = query.substringFromIndex("code=".endIndex)
            
            print(code)
            
            // 获取到 code 之后, 在这里调用方法请求 access_token, 并且将isRequestSuccessClosuer闭包所要执行的代码写好
            RSUserAccoutViewModel.sharedUserAccountViewModel.requestAccess_TokenWithCode(code, isRequestSuccessClosuer: { (isSuccess) in
                if isSuccess{
                
                    print("登录成功")
                    
                    // 先把自己dismiss掉, 再通知切换根控制器
                    self.dismissViewControllerAnimated(false, completion: { 
                        // 发送通知, 把自己当做参数传递给监听者
                        NSNotificationCenter.defaultCenter().postNotificationName(changeRootViewController, object: self)
                    })
                    
                    
                    
                }else{
                
                    print("登录失败")
                    
                }
            })
            
//            requestAccess_TokenWithCode(code)
            
        }else{
        
            // 如果用户在是否授权页面点击了"取消", 那么将返回上一级控制器
            dismissViewControllerAnimated(true, completion: nil)
        }
        
        return false
    }
    
        
    
}




// 加载旋转的视图, 遵守代理协议
extension RSOauthViewController: UIWebViewDelegate{

    // MARK: 当加载开始的时候
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
        
    }
    // 结束的时候
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    // 加载失败的时候
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }

}



























